package com.ccf.business.database.controller;

import cn.hutool.core.util.StrUtil;
import com.ccf.business.database.model.Datasource;
import com.ccf.business.database.model.vo.TableVO;
import com.ccf.business.database.service.IDatasourceService;
import com.service.database.config.DataBase;
import com.common.model.pojo.Query;
import com.common.model.result.PageResult;
import com.common.model.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 数据源管理
 * @author ccf
 * @date 2021-11-25 16:42:29
 */
@Slf4j
@RestController
@RequestMapping("/datasource")
@Api(tags = "数据源管理")
public class DatasourceController {
    @Autowired
    private IDatasourceService datasourceService;

    /**
     * 列表
     */
    @ApiOperation(value = "分页查询列表")
    @GetMapping
    public PageResult list(Query query) {
        return datasourceService.findList(query);
    }


    /**
     * 查询
     */
    @ApiOperation(value = "查询")
    @GetMapping("/{id}")
    public Result getById(@PathVariable String id) {
        Datasource model = datasourceService.getById(id);
        return Result.succeed(model, "查询成功");
    }

    /**
     * 新增or更新
     */
    @ApiOperation(value = "保存")
    @PostMapping
    public Result save(@RequestBody Datasource datasource) {
        datasource.setCreator("1");
        if (datasourceService.isExistName(datasource.getId(), datasource.getName())){
            return Result.failed("名称已存在");
        }
        datasourceService.submit(datasource);
        return Result.succeed("保存成功");
    }

    /**
     * 删除
     */
    @ApiOperation(value = "删除")
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable String id) {
        //批量删除
        if (StrUtil.contains(id, ",")){
            String[] ids = StrUtil.split(id, ",");
            datasourceService.removeByIds(Arrays.stream(ids).collect(Collectors.toList()));
        } else {
            datasourceService.removeById(id);
        }
        return Result.succeed("删除成功");
    }

    /**
     * 查询数据源下的所有表
     */
    @ApiOperation(value = "查询数据源下的所有表")
    @GetMapping("/{id}/tables")
    public Result tables(@PathVariable String id) {
        List tables = null;
        try {
            tables = datasourceService.listTables(id);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed("查询出错："+ e.getMessage());
        }
        return Result.succeed(tables, "查询成功");
    }


    /**
     * 查询数据源下的所有可操作表
     */
    @ApiOperation(value = "查询数据源下的所有可操作表")
    @GetMapping("/{id}/tablesBySelfBuilt")
    public Result tablesBySelfBuilt(@PathVariable String id) {
        List tables = null;
        try {
            tables = datasourceService.listTablesBySelfBuilt(id);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed("查询出错："+ e.getMessage());
        }
        return Result.succeed(tables, "查询成功");
    }

    /**
     * 查询表结构和表数据
     */
    @ApiOperation(value = "查询表结构和表数据")
    @GetMapping("/{id}/{tableName}/{page}/{pageSize}")
    public Result tableDesc(@PathVariable String id, @PathVariable String tableName, @PathVariable String page, @PathVariable String pageSize) {
        if(StrUtil.isEmpty(page)){
            page = "1";
        }
        if(StrUtil.isEmpty(pageSize)){
            pageSize = "50";
        }
        TableVO vo = null;
        try {
            vo = datasourceService.getTable(id, tableName, page, pageSize);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed("查询出错："+ e.getMessage());
        }
        return Result.succeed(vo, "查询成功");
    }

    /**
     * 查询表结构
     */
    @ApiOperation(value = "查询表字段")
    @GetMapping("/{id}/{tableName}/fields")
    public Result tableInfo(@PathVariable String id, @PathVariable String tableName)  {
        List<Map<String, Object>> tableDesc = null;
        try {
            tableDesc = datasourceService.getTableDesc(id, tableName);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed("查询出错："+ e.getMessage());
        }
        return Result.succeed(tableDesc, "查询成功");
    }


    /**
     * 测试连接
     */
    @ApiOperation(value = "测试连接")
    @PostMapping("/connect")
    public Result connect(@RequestBody Datasource datasource) {
        boolean connect = datasourceService.connect(datasource);
        return Result.status(connect, "","连接成功", "连接失败");
    }



    /**
     * 获取支持的数据库类型
     */
    @ApiOperation(value = "获取支持的数据库类型")
    @GetMapping("/types")
    public Result types() {
        List<String> types = DataBase.getList();
        return Result.succeed(types, "查询成功");
    }



    /**
     * 搜索表名
     */
    @ApiOperation(value = "全局搜索表名")
    @GetMapping("/search/tables")
    public Result searchTable(String keyword, String datasourceId) {
        List tables = null;
        try {
            tables = datasourceService.searchTables(keyword, datasourceId);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed("查询出错："+ e.getMessage());
        }
        return Result.succeed(tables, "查询成功");
    }

    /**
     * 搜索字段值并去重
     */
    @ApiOperation(value = "搜索字段值并去重")
    @GetMapping("/{id}/{tableName}/fields/{fieldName}")
    public Result searchFieldValue(@PathVariable String id, @PathVariable String tableName,  @PathVariable String fieldName) {
        List vals = null;
        try {
            vals = datasourceService.searchFieldValue(id, tableName, fieldName);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed("查询出错："+ e.getMessage());
        }
        return Result.succeed(vals, "查询成功");
    }


}
